package cn.rcth.task;

import cn.rcth.base.constants.BaiseConstants;
import cn.rcth.base.domain.*;
import cn.rcth.base.enums.ErrorCode;
import cn.rcth.base.mapper.*;
import cn.rcth.base.msg.EchostrMsg;
import cn.rcth.base.serivce.IFormIdSerivce;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import sun.applet.Main;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时器
 */
@Component
public class OrderTask {

    public static final int TWOHOURS = 2 * 60 * 60 * 1000;//两个小时后

    public static final int SEVENDAYS = 7 * 24 * 60 * 60 * 1000;//7天后


    /**
     * 每天凌晨两点执行
     * 用户收货后七天之后自动支付
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void orderServenSchedul() throws Exception {
        timerToModifyOrderStatus(SEVENDAYS,
                BaiseConstants.ORDER_PENDING_RECEIPT,
                BaiseConstants.ORDER_ACCEPTED);

    }

    /**
     * 1分钟执行一次
     * 用户未支付,两个小时后取消订单
     */
    @Scheduled(cron = "0 0/2 * * * ? ")
    public void orderScheduled() throws Exception {
        timerToModifyOrderStatus(TWOHOURS,
                BaiseConstants.ORDER_TO_BE_PAID,
                BaiseConstants.ORDER_CANCELLED);
    }

    /**
     * 每1天执行一次
     * 根据订单状态发送模板消息
     */
    @Scheduled(cron = "0 0 */1 * * ? ")  //"0 0/2 * * * ? "   "0 0 */1 * * ? "
    public void timedPushMessage() {
        //查询所有订单
        List<Order> orders = orderMapper.selectAll();
        for (Order order : orders) {
            Long userId = order.getUserId();
            Long orderId = order.getId();
            //form id
            FormId formId = formIdMapper.selectformByUserIdByOrderId(userId, orderId);
            if (formId != null) {
                if (order.getStatus().equals(30)) {
                    //调用推送发货消息
                    formIdSerivce.pushOneUser(userId, formId.getFormTwo(),
                            orderId, BaiseConstants.template_receipt);

                } else if (order.getStatus().equals(40)) {
                    //推送已收货消息
                    formIdSerivce.pushOneUser(userId, formId.getFormOne(),
                            orderId, BaiseConstants.template_complete);
                }
            }
        }
    }


    /**
     * 定时器修改订单方法
     *
     * @param date        时间间距
     * @param statusAgo   修改前状态
     * @param statusLater 修改后状态
     */
    public void timerToModifyOrderStatus(int date, Integer statusAgo, Integer statusLater) throws Exception {
        List<Order> orders = orderMapper.getOrderByOrderStatus(statusAgo);
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Order order : orders) {
            Date cancelTime;
            if (statusAgo.equals(BaiseConstants.ORDER_TO_BE_PAID)) {
                cancelTime = order.getCreateTime();
            } else {
                cancelTime = order.getPoyTime();
            }
            String format = dateformat.format(cancelTime);
            try {
                Date date1 = new Date();
                long time = dateformat.parse(format).getTime() + date;
                if (date1.getTime() > time) {
                    order.setStatus(statusLater);
                    order.setModifyTime(new Date());
                    order.setModifyId(order.getUserId());
                    if (statusAgo.equals(BaiseConstants.ORDER_TO_BE_PAID)) {
                        order.setCancelTime(date1);
                        List<OrderProduct> orderProducts = orderProductMapper.selestOrderProductByOrderId(order.getId());
                        for (OrderProduct orderProduct : orderProducts) {
                            Product product = productMapper.selectByPrimaryKey(orderProduct.getProductId());
                            product.setStorage(product.getStorage() + orderProduct.getCount());
                            product.setModifyTime(date1);
                            product.setModifyId(order.getUserId());
                            productMapper.updateByPrimaryKey(product);
                        }
                    }else {
                        order.setReceiveTime(new Date());
                        Delivery delivery = deliveryMapper.selectDeliveryByOrderId(order.getId());
                        delivery.setCreateTime(new Date());
                        deliveryMapper.update(delivery);
                    }

                    orderMapper.updateByPrimaryKey(order);
                }
            } catch (Exception e) {
                e.getMessage();
            }
        }
    }
















    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderProductMapper orderProductMapper;

    @Autowired
    private FormIdMapper formIdMapper;

    @Autowired
    private IFormIdSerivce formIdSerivce;

    @Autowired
    private DeliveryMapper deliveryMapper;



}
